<template>
    <div class="area-select">
        <popup :open.sync="show" @confirm="confirm" @cancel="cancel" :title="title" :mask="mask" :showHeader="showHeader">
            <div class="wheel">
                <brsSelect :list="province_list" :defaultIndex="selectIndex[0]" @change="provinceChange"></brsSelect>
                <template v-if="city_list.length">
                    <brsSelect :list="city_list" :defaultIndex="selectIndex[1]" @change="cityChange"></brsSelect>
                </template>
                <template v-if="county_list.length">
                    <brsSelect :list="county_list" :defaultIndex="selectIndex[2]" @change="countyChange"></brsSelect>
                </template>
            </div>
        </popup>
    </div>
</template>

<script>
import popup from "@/components/popup"
import brsSelect from "@/components/select"
import { objectToArray } from "@/utils/utils"
const areaData = window.vantArea;
const province_list = objectToArray(areaData.province_list);
const city_list = objectToArray(areaData.city_list);
const county_list = objectToArray(areaData.county_list);
export default {
    name: 'area-select',
    props: {
        open: {
            type: Boolean,
            default: false
        }, // 是否显示 area-select
        defaultChange: {
            type: Array,
            default(){
                return ["110000", "110100", "110101"]
            }
        }, // 默认值 北京市 北京市 东城区
        mask: {
            type: Boolean,
            default: true
        },
        showHeader: {
            type: Boolean,
            default: true
        },
        title: {
            type: String,
            default: ''
        }
    },
    components: { popup, brsSelect },
    data(){
        return {
            province_list: province_list,
            city_list: [],
            county_list: [],
            selectIndex: [0, 0, 0], // 默认选中的index
            show: false, // 是否显示 popup
            changeList: [], // 默认地区码
        }
    },
    watch: {
        open(val){
            this.show = val
            if(val){
                this.$nextTick(() => {
                    this.initData()
                })
            }
        }
    },
    methods: {
        cancel(){
            this.show = false;
            this.$emit('update:open', false);
            this.$emit('cancel');
        },
        confirm(){
            let province = this.province_list.filter((el, index) => index === this.selectIndex[0])[0]
            let city = this.city_list.filter((el, index) => index === this.selectIndex[1])[0]
            let county = this.county_list.filter((el, index) => index === this.selectIndex[2])[0]
            this.show = false;
            this.$emit('update:open', false);
            this.$emit('confirm', {province, city, county});
        },
        /**
         * 根据地区码获取下级地区列表
         *
         * @param   {String}  code   地区码
         * @param   {Number}  level  1：获取市级，2：获取县级 默认：1
         *
         * @return  {Array} 返回地区列表
         */
        getChildrenList(code, level = 1){
            return new Promise(resolve => {
                let prefix = ''; // 需要匹配的前缀
                let array = []; // 需要循环的数组
                let index = 2; // 需要匹配的前缀的长度
                let returnArray = [];
                if(level === 1){
                    prefix = code.substring(0, 2);
                    array = city_list;
                    index = 2;
                }else if(level === 2){
                    prefix = code.substring(0, 4);
                    array = county_list;
                    index = 4;
                }
                array.map((el, i) => {
                    const pre = el.id.substring(0, index);
                    if(prefix === pre){
                        returnArray.push(el)
                    }
                    if(i === (array.length - 1)){
                        resolve(returnArray);
                    }
                })
            })
        },
        // 省选择
        async provinceChange(index){
            this.$set(this.selectIndex, 0, index)
            let cityList = await this.getChildrenList(province_list[index].id, 1)
            if(cityList.length){
                this.city_list = cityList;
                this.$set(this.selectIndex, 1, 0)
                let countyList = await this.getChildrenList(this.city_list[0].id, 2)
                if(countyList.length){
                    this.county_list = countyList;
                    this.$set(this.selectIndex, 2, 0)
                }
            }
        },
        // 市选择
        async cityChange(index){
            this.$set(this.selectIndex, 1, index)
            let countyList = await this.getChildrenList(this.city_list[index].id, 2)
            if(countyList.length){
                this.county_list = countyList;
                this.$set(this.selectIndex, 2, 0)
            }
        },
        // 区县选择
        countyChange(index){
            this.$set(this.selectIndex, 2, index)
        },
        /**
         * 获取code的index
         *
         * @param   {Array}  array  需要循环的数组
         * @param   {String}  code   地区码
         *
         * @return  {Number} index值
         */
        getSelectIndex(array, code){
            let returnIndex = null;
            for (let index = 0; index < array.length; index++) {
                const element = array[index];
                if(element.id === code){
                    returnIndex = index;
                    break;
                }
            }
            return returnIndex;
        },
        /**
         * 初始化默认值
         */
        async initData(){
            if(!this.defaultChange || !this.defaultChange.length){
                this.changeList = ["110000", "110100", "110101"]
            }else{
                this.changeList = this.defaultChange
            }
            let provinceIndex = this.getSelectIndex(this.province_list, this.changeList[0])
            if(provinceIndex !== null){
                this.$set(this.selectIndex, 0, provinceIndex)
                let cityList = await this.getChildrenList(this.province_list[provinceIndex].id, 1)
                if(cityList.length){
                    let cityIndex = this.getSelectIndex(cityList, this.changeList[1])
                    if(cityIndex !== null){
                        this.city_list = cityList;
                        this.$set(this.selectIndex, 1, cityIndex)
                        let countyList = await this.getChildrenList(this.city_list[cityIndex].id, 2)
                        if(countyList.length){
                            let countyIndex = this.getSelectIndex(countyList, this.changeList[2])
                            if(countyIndex !== null){
                                this.county_list = countyList;
                                this.$set(this.selectIndex, 2, countyIndex)
                            }
                        }
                    }
                }
            }
        }
    }
}
</script>

<style lang="less" scoped>
.wheel{
    display: flex;
    /deep/ .brs-select{
        flex: 1;
    }
}
</style>